package com.example.boot.rabbitmq.producer.rest;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 * @author ccubee
 * @since 21-3-7 21:36
 */
@Component
public class RabbitSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 确认消息的回调监听接口 用于确认消息被broken收到
     */
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        /**
         *
         * @param correlationData 唯一标识
         * @param ack broken是否落盘成功
         * @param cause 失败的一些异常信息
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {

        }
    };


    public void send(Object message, Map<String, Object> properties) {
        MessageHeaders headers = new MessageHeaders(properties);

        Message<Object> msg = MessageBuilder.createMessage(message, headers);

        rabbitTemplate.setConfirmCallback(confirmCallback);

        // 指定业务唯一id
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());

        rabbitTemplate.convertAndSend("exchange", "springboot.rabbit", msg, new MessagePostProcessor() {
            @Override
            public org.springframework.amqp.core.Message postProcessMessage(org.springframework.amqp.core.Message message) throws AmqpException {
                return null;
            }
        }, correlationData);

        rabbitTemplate.convertAndSend("exchange", "springboot.rabbit", msg, correlationData);



    }
}
